package com.sanjishu.enterlab.electricity.sale.controller.manage;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.domain.City;
import com.sanjishu.enterlab.electricity.sale.domain.User;
import com.sanjishu.enterlab.electricity.sale.domain.UserCityRole;
import com.sanjishu.enterlab.electricity.sale.service.CityService;
import com.sanjishu.enterlab.electricity.sale.service.UserCityRoleService;
import com.sanjishu.enterlab.electricity.sale.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("manage/dataSetting")
public class DataRoleSettingController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserCityRoleService userCityRoleService;
    @Autowired
    private CityService cityService;

    @RequestMapping(value = "sales", method = RequestMethod.GET)
    public String saleList(Model model) {
        List<User> userList = userService.findSales();
        model.addAttribute("userList", userList);
        return "manage/dataSetting/index";
    }

    @RequestMapping(value = "showData/{userId}", method = RequestMethod.GET)
    public String showData(@PathVariable Integer userId, Model model) {
        List<Integer> cityIdList = userCityRoleService.listCityIdByUserId(userId);
        List<City> cityList = cityService.getCityList();
        HashMap<String, List<City>> cityMap = cityService.returnCityMap();
        model.addAttribute("cityIdList", cityIdList);
        model.addAttribute("cityList", cityList);
        model.addAttribute("cityMap", cityMap);
        model.addAttribute("userId", userId);
        return "manage/dataSetting/showCity";
    }

    @RequestMapping(value = "saveSetting", method = RequestMethod.POST)
    @ResponseBody
    public Response saveSetting(Integer userId, @RequestParam(value = "cityIds[]", required = false) Integer[] cityIds) {
        return userCityRoleService.saveSetting(userId, cityIds);
    }


    @RequestMapping(value = "createSale", method = RequestMethod.POST)
    @ResponseBody
    public Response createSale(String name, String phone, Integer types) {
        userService.insert(phone, DigestUtils.md5Hex("123456"), null, types, name);
        return Response.buildSuccess("创建成功。");
    }

    @RequestMapping(value = "deleteSale", method = RequestMethod.POST)
    @ResponseBody
    public Response deleteSale(Integer userId) {
        userService.deleteSale(userId);
        return Response.buildSuccess("删除成功。");
    }

}
